<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible">
    <el-form :model="categoryData">
      <el-form-item label="名称" :label-width="formLabelWidth">
        <el-input v-model="categoryData.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="排序" :label-width="formLabelWidth">
        <el-input v-model="categoryData.sort" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {
  categoryCreateOrUpdate,
  getAllResourceCategory,
} from "@/api/resource-category";
export default {
  name: "ResourceCategoryCreateOrEdit",
  data() {
    return {
      dialogFormVisible: false,
      isCreate: true,
      categoryData: {
        id: undefined,
        name: "",
        sort: 0,
      },
      formLabelWidth: "120px",
    };
  },
  computed: {
    title() {
      return this.isCreate ? "新建" : "编辑";
    },
  },
  methods: {
    onSubmit() {
      categoryCreateOrUpdate(this.categoryData).then((res) => {
        if (res.data.data) {
          this.$message.success(`${this.title}资源类别成功！`);
          this.$emit("changeCategory"); //告诉父组件需要刷新数据
        } else {
          this.$message.error(`${this.title}资源类别失败~`);
        }
        this.dialogFormVisible = false;
        console.log(res);
      });
    },
    //封装方法显示对话框
    showAndInit(categoryId = 0) {
      //小于1创建,显示
      this.isCreate = categoryId < 1;
      this.dialogFormVisible = true;
      if (this.isCreate) {
        console.log("新建");
        this.categoryData = { id: undefined, name: "", sort: 0 };
      } else {
        console.log("编辑");
        getAllResourceCategory().then((res) => {
          if (res.data.code === "000000") {
            const categoryData = res.data.data.find(
              (item) => item.id === categoryId
            );
            this.categoryData = categoryData;
          }
          console.log("点编辑获得的内容", res);
        });
      }
    },
  },
};
</script>
<style lang="scss" scoped></style>
